// pages/balance/balance.js
const util = require('../../utils/util.js')
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    addrInfo:{
      myAddr:'请选择收货地址',
    },
    flag:true,
    totalPrice: 0,
    carts: [
     
    ],
    orderId:null,
  },
  // singleprice:function(carts){
  //   let list = carts
  //   for (let cart of list) {
  //     cart.singleprice=cart.num * cart.price;
  //   }
  //   this.setData({
  //     carts:list
  //   })
  // },
  getTotalPrice: function () {
    let carts = this.data.carts;
    let total = 0;
    for (let i = 0; i < carts.length; i++) {
      total += carts[i].cost;
    }
    console.log(total)
    console.log(this.data.totalPostage)
    total += parseFloat(this.data.totalPostage);
    console.log(total)
    this.setData({
      totalPrice: parseFloat(total).toFixed(2)
    })
  },
  getTotalPostage:function(){
    let carts = this.data.carts;
    let total = 0;
    for (let i = 0; i < carts.length; i++) {
      total += carts[i].postage;
    }
    this.setData({
      totalPostage: parseFloat(total).toFixed(2)
    },()=>{
      return;
    })
  },

  chooseAddr(){
    wx.navigateTo({
      url: '../myAddr/myAddr',
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options);
    const cart = JSON.parse(options.carts);
    let carts = []
    if (toString.call(cart) === '[object Object]')
    {
      carts.push(cart)
    }
    else if(toString.call(cart) === '[object Array]'){
       carts = cart;
    }
    carts.map((item,index)=>{
      item.pictureUrl = decodeURIComponent(item.pictureUrl);
    })
    this.setData({
      carts,
    })
    this.getTotalPostage()
    this.getTotalPrice();
    
  },

  createOrder(){
    let that = this;
    if(!this.data.flag){
      let carts =  this.data.carts
      const { myAddr, addressType, consignee, mobile } = this.data.addrInfo;
      const ids = []
      for(let i =0;i<carts.length;i++){
        ids.push(carts[i].id);
      }
      console.log(
        myAddr+'--',
        addressType+'--',
        consignee+'--',
        mobile+'--',
        ids
      )
      util.post({
        url:'https://groomtea.icebartech.com/api/miniApp/order/createOrder',
        data:{
          address:myAddr,
          addressType,
          consignee,
          mobile,
          ids
        },
        success:res=>{
          console.log(res);
          for(let j=0;j<carts.length;j++){
            util.post({
              url: 'https://groomtea.icebartech.com/api/miniApp/shoppingTrolley/deletedShoppingTrolley',
              header: { 'content-type': 'application/x-www-form-urlencoded' },
              data:{
                id:carts[j].id
              },
              success:delRes=>{
                console.log(delRes)
              },
              fail:err=>{
                console.log(err);
              }
            })
          }
          that.data.orderId = res.data.bussData;
          that.toPay();
        },
        fail:err=>{
          console.log(err)
        }
      })
    }
    else app.titleToast("请选择地址")
  },
  toPay(){
    let openId = wx.getStorageSync('openId'),
      orderId = this.data.orderId,
      that = this;
      if(orderId){
        console.log(openId);
        console.log(orderId);
        util.post({
          url: 'https://groomtea.icebartech.com/api/miniApp/order/orderPay',
          data: {
            openId: openId,
            orderId: orderId
          },
          success: res => {
            let result = JSON.parse(res.data.bussData);
            result['success'] = (res) => {
              console.log(res);
              wx.reLaunch({
                url: '../payRes/payRes?orderId=' + result.id,
              })
            }
            result['fail'] = (err) => {
              console.log(err);
            }
            wx.requestPayment(result);

          },
          fail: err => {
            console.log(err);
          }
        })
      }
      else{
        this.createOrder();
      }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if(this.data.addrInfo.myAddr != '请选择收货地址'){
      this.setData({
        flag:false
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
})